package offer.tree;

import java.util.ArrayList;
import java.util.Stack;

/**
 * @author DengYuan2
 * @create 2021-02-27 19:50
 */
public class n_32_3 {
    public static void main(String[] args) {
        n_32_3 n = new n_32_3();
        TreeNode t1 = new TreeNode(8);
        TreeNode t2 = new TreeNode(6);
        TreeNode t3 = new TreeNode(10);
        TreeNode t4 = new TreeNode(5);
        TreeNode t5 = new TreeNode(7);
        TreeNode t6 = new TreeNode(9);
        TreeNode t7 = new TreeNode(11);
        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t2.right = t5;
        t3.left = t6;
        t3.right = t7;
        ArrayList<ArrayList<Integer>> res = n.Print(t1);
        System.out.println(res);
    }

    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (pRoot==null){
            return res;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(pRoot);
        while (!stack1.isEmpty()||!stack2.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>();
            if (!stack1.isEmpty()){
                while (!stack1.isEmpty()){

                    TreeNode parent = stack1.pop();
                    if (parent.left!=null){
                        stack2.push(parent.left);
                    }
                    if (parent.right!=null){
                        stack2.push(parent.right);
                    }
                    list.add(parent.val);
                }
            }else {
                while (!stack2.isEmpty()){
                    TreeNode node = stack2.pop();
                    if (node.right!=null){
                        stack1.push(node.right);
                    }
                    if (node.left!=null){
                        stack1.push(node.left);
                    }
                    list.add(node.val);
                }
            }
            res.add(list);
        }
        return res;

    }


}
